<template>
  <el-dialog v-model="visible" @close="close" :append-to-body="true" width="750px" title="客户机会">
    <el-form ref="formRef" :model="formData" :rules="formRules" size="small" label-width="120px">
      <el-row style="margin-bottom: 18px">
        <el-col :span="12">
          <el-form-item label="产品线" prop="productLineName">
            <el-select v-model="formData.productLineName" placeholder="请选择产品线" allow-create default-first-option filterable clearable @change="productChange" size="small" style="width: 100%">
              <el-option v-for="item in productLineList" :key="item.name" :label="item.name" :value="item.name"/>
            </el-select>
          </el-form-item>
          <el-form-item label="线索归属部门" prop="deptId">
            <el-select v-model="formData.deptId" size="small" style="width: 100%" placeholder="请选择线索归属部门" clearable @change="getClueUsers">
              <el-option v-for="item in deptList" :key="item.id" :value="item.id" :label="item.name"/>
            </el-select>
          </el-form-item>
          <el-form-item label="预估签约日期" prop="signDate">
            <el-date-picker v-model="formData.signDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" :clearable="false" placeholder="请选择" :disabled-date="time => time.getTime() <= (Date.now() - 8.64e7)" style="width: 100%"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="机会阶段" prop="stageId">
            <el-select v-model="formData.stageId" placeholder="请选择阶段" style="width: 100%">
              <el-option v-for="item in stageList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="线索归属人" prop="belongId">
            <el-select v-model="formData.belongId" placeholder="请选择线索归属人" size="small" style="width: 100%" clearable>
              <el-option v-for="item in belongList" :key="item.userId" :label="item.nickname" :value="item.userId"/>
            </el-select>
          </el-form-item>
          <el-form-item label="预计签约金额(元)" prop="signAmount">
            <el-input-number v-model="formData.signAmount" style="width: 100%" :min="0" :controls="false"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="签约可能性(%)" prop="probability">
        <el-input-number v-model="formData.probability" style="width: 150px" :min="1" :max="100" :controls="false"/>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" :rows="3" type="textarea"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button size="small" @click="close">取消</el-button>
      <el-button type="primary" size="small" :loading="submitLoad" @click="submit(formRef)">提交</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {computed, reactive, ref, toRefs} from 'vue'
import {ElMessage} from 'element-plus'
import customerApi from '/@/api/ums/customer'
import opportunityApi from '/@/api/ums/customer/opportunity'
import opportunityStageApi from '/@/api/ums/customer/opportunityStage'
import {getDeptUsers, getEnterpriseUsers} from '/@/api/sys/user'
import {getDeptSelector} from '/@/api/sys/dept'

export default {
  name: 'OpportunityForm',
  emits: ['update:dialogPop', 'callback'],
  props: {
    // 控制显示隐藏
    dialogPop: {
      type: Boolean,
      default: false
    },
    // 产品线主键
    defaultForm: {
      type: Object,
      default: null
    }
  },
  setup(props, context) {
    const formRef = ref()
    const {dialogPop, defaultForm} = toRefs(props)
    const visible = computed({
      get: () => {
        if (dialogPop.value) {
          if (defaultForm.value.id) {
            state.formData = JSON.parse(JSON.stringify(defaultForm.value))
          } else {
            state.formData.customerId = defaultForm.value.customerId
          }
          getDeptSelector().then(res => state.deptList = res.data)
          opportunityStageApi.getList().then(res => state.stageList = res.data).catch(e => console.log(e))
          customerApi.getProductLines().then(res => state.productLineList = res.data).catch(e => console.log(e))
          getEnterpriseUsers().then(res => state.belongList = state.enterpriseUsers = res.data).catch(e => console.log(e))
        }
        return dialogPop.value
      },
      set: (val) => context.emit('update:dialogPop', val)
    })

    const state = reactive({
      formData: {
        id: null,
        customerId: null,
        stageId: null,
        deptId: null,
        belongId: null,
        productLineId: null,
        productLineName: null,
        signDate: null,
        signAmount: null,
        probability: null,
        remark: null
      },
      formRules: {
        productLineName: {required: true, trigger: 'blur', message: '请选择产品线'},
        stageId: {required: true, trigger: 'blur', message: '请选择机会阶段'}
      },
      submitLoad: false,
      stageList: [],
      productLineList: [],
      deptList: [],
      belongList: [],
      enterpriseUsers: []
    })

    // 选中某个产品
    const productChange = (productName) => {
      state.formData.productLineId = null
      for (let i = 0; i < state.productLineList.length; i++) {
        let item = state.productLineList[i]
        if (item.name == productName && item.id) {
          state.formData.productLineId = item.id
          break
        }
      }
    }
    // 获取线索归属人
    const getClueUsers = (deptId) => {
      if (deptId) {
        getDeptUsers(deptId).then(res => state.belongList = res.data).catch(e => console.log(e))
      } else {
        state.belongList = state.enterpriseUsers
      }
    }
    // 关闭表单
    const close = () => context.emit('callback')
    // 提交保存
    const submit = (formEl) => {
      formEl.validate(async (valid) => {
        if (!valid) return
        let res
        state.submitLoad = true
        try {
          if (state.formData.id) {
            res = await opportunityApi.editData(state.formData)
          } else {
            res = await opportunityApi.addOpportunity(state.formData)
          }
          if (res.data) {
            ElMessage.success('保存成功！')
            state.submitLoad = false
            context.emit('update:dialogPop', false)
            context.emit('callback')
          }
        } catch (e) {
          console.log(e)
          state.submitLoad = false
        }
      })
    }

    return {
      visible,
      formRef,
      ...toRefs(state),
      submit,
      close,
      productChange,
      getClueUsers
    }
  }
}
</script>

<style scoped lang="scss">

</style>
